//
//  FogetSecreateViewController.m
//  BigToBig
//
//  Created by admin on 16/4/28.
//  Copyright © 2016年 cn.cloudtp. All rights reserved.
//

#import "FogetSecreateViewController.h"

@interface FogetSecreateViewController()<UITextFieldDelegate,UIScrollViewDelegate>

@property (weak ,nonatomic)UIScrollView *scrollView;
@property (strong ,nonatomic)UIPageControl *pageControl;
@property (weak ,nonatomic)UITextField *inputPhoneNubText;
@property (weak ,nonatomic)UITextField *inputSecurityCodeText;
@property (weak ,nonatomic)UITextField *inputSecreatText;
@property (weak ,nonatomic)UITextField *sureSecreatText;
@property (weak ,nonatomic)UIButton *getSecurityCodeBtn;
//@property (weak ,nonatomic)UITextField *inputNameNubText;
//@property (weak ,nonatomic)UIButton *agreeCircleBtn;

@end

@implementation FogetSecreateViewController


- (void)viewDidLoad{
    
    [super viewDidLoad];

    [self makeUI];

}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}
- (void)makeUI{
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.titleView.tintColor = [UIColor whiteColor];
    UILabel *title = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 40, 40)];
    title.textAlignment = NSTextAlignmentCenter;
    title.text = @"忘记密码";
    title.textColor = [UIColor grayColor];
    self.navigationItem.titleView = title;
    //自动调整scrollview的 inset,设置为no，不让viewController调整比如两个tableview从第一个push到第二个第一个设置frame(0,0,w,h)没问题push到第二个就被导航栏遮住部分cell必须设置成（0，64，w,h）都是因为automaticallyAdjustsScrollViewInsets的原因设置成no就好了所有这里是为了防止scrollview滑动回来的时候被导航栏遮住一块
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    
    UIPageControl* pageControl = [[UIPageControl alloc] init];
    pageControl.numberOfPages = 3;
    self.pageControl = pageControl;
    
    
    UIScrollView *scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 64, kScreenWidth, kScreenHeight - 64)];
    //隐藏水平方向的滚动条
    scrollView.userInteractionEnabled = YES;
    scrollView.showsHorizontalScrollIndicator = NO;
    //开启分页
    scrollView.pagingEnabled = YES;
    //监听滑动-->成为代理
    scrollView.delegate = self;
    scrollView.contentSize = CGSizeMake(scrollView.bounds.size.width * 3, 0);
    scrollView.backgroundColor = [UIColor colorWithRed:240/255.0 green:239/255.0 blue:237/255.0 alpha:1];
    scrollView.bounces = NO;
    scrollView.scrollEnabled = NO;
    self.scrollView = scrollView;
    
    [self.view addSubview:scrollView];
    [self addReginsterView:scrollView];
    
}

- (void)addReginsterView:(UIScrollView *)reginsterView{
    
    
    for (int y = 0; y < 2; y++) {
        
        if (y == 0) {
            
            
            UIButton *nextBtn = [[UIButton alloc]initWithFrame:CGRectMake(10 + y*kScreenWidth, 146, kScreenWidth - 20, 45)];
            nextBtn.backgroundColor = [UIColor colorWithRed:92/255.0 green:167/255.0 blue:252/255.0 alpha:1];
            [nextBtn setTitle:@"下一步" forState:UIControlStateNormal];
            [nextBtn addTarget:self action:@selector(next) forControlEvents:UIControlEventTouchUpInside];
            nextBtn.layer.cornerRadius = 5.0f;
            [nextBtn.layer setMasksToBounds:YES];
            [reginsterView addSubview:nextBtn];
            
            
            for (int i = 0; i < 2; i++) {
                
                
                UIView *view = [[UIView alloc]initWithFrame:CGRectMake(y * kScreenWidth,i *55 + 15, kScreenWidth, 45)];
                view.backgroundColor = [UIColor whiteColor];
                [reginsterView addSubview:view];
                if (i == 0) {
                    
                    UITextField *inputPhoneNubText = [[UITextField alloc]initWithFrame:CGRectMake(10, 0, kScreenWidth - 110, 45)];
                    inputPhoneNubText.textAlignment = NSTextAlignmentLeft;
                    inputPhoneNubText.textColor = [UIColor grayColor];
                    inputPhoneNubText.placeholder = @"请输入账号";
                    inputPhoneNubText.clearButtonMode = UITextFieldViewModeAlways;
                    inputPhoneNubText.delegate = self;
//                    inputPhoneNubText.keyboardType = UIKeyboardTypeNumberPad;
                    self.inputPhoneNubText = inputPhoneNubText;
                    UIButton *getSecurityCodeBtn = [[UIButton alloc]initWithFrame:CGRectMake(kScreenWidth - 100, 7.5, 80, 30)];
                    [getSecurityCodeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
                    [getSecurityCodeBtn setTitleColor:[UIColor colorWithRed:92/255.0 green:167/255.0 blue:252/255.0 alpha:1] forState:UIControlStateNormal];
                    getSecurityCodeBtn.titleLabel.font = [UIFont systemFontOfSize:12.0];
                    getSecurityCodeBtn.layer.cornerRadius = 2.0f;
                    [getSecurityCodeBtn.layer setMasksToBounds:YES];
                    self.getSecurityCodeBtn = getSecurityCodeBtn;
                    [getSecurityCodeBtn addTarget:self action:@selector(getSecurityCode) forControlEvents:UIControlEventTouchUpInside];
                    [getSecurityCodeBtn.layer setBorderColor:[UIColor colorWithRed:92/255.0 green:167/255.0 blue:252/255.0 alpha:1].CGColor];
                    [getSecurityCodeBtn.layer setBorderWidth:1];
                    getSecurityCodeBtn.backgroundColor = [UIColor whiteColor];
                    
                    [view addSubview:getSecurityCodeBtn];
                    [view addSubview:inputPhoneNubText];
                    
                }
                if (i == 1) {
                    
                    UITextField *inputSecurityCodeText = [[UITextField alloc]initWithFrame:CGRectMake(10, 0, kScreenWidth - 150, 45)];
                    inputSecurityCodeText.textAlignment = NSTextAlignmentLeft;
                    inputSecurityCodeText.delegate = self;
                    inputSecurityCodeText.textColor = [UIColor grayColor];
                    inputSecurityCodeText.placeholder = @"请输入验证码";
                    self.inputSecurityCodeText = inputSecurityCodeText;
                    self.inputSecurityCodeText.keyboardType = UIKeyboardTypeNumberPad;
                    [view addSubview:inputSecurityCodeText];
                    
                    
                }
                
                
            }
            
        }
        else if(y == 1) {
            
            
            UIButton *nextBtn = [[UIButton alloc]initWithFrame:CGRectMake(10 + y*kScreenWidth, 145, kScreenWidth - 20, 45)];
            nextBtn.backgroundColor = [UIColor colorWithRed:92/255.0 green:167/255.0 blue:252/255.0 alpha:1];
            [nextBtn setTitle:@"完成" forState:UIControlStateNormal];
            [nextBtn addTarget:self action:@selector(complate) forControlEvents:UIControlEventTouchUpInside];
            nextBtn.layer.cornerRadius = 5.0f;
            [nextBtn.layer setMasksToBounds:YES];
            [reginsterView addSubview:nextBtn];
            


            for (int i = 0; i < 2; i++) {
                
                
                UIView *view = [[UIView alloc]initWithFrame:CGRectMake(y * kScreenWidth,i *55 + 15, kScreenWidth, 45)];
                view.backgroundColor = [UIColor whiteColor];
                [reginsterView addSubview:view];
                
                if (i == 0) {
                    
                    UITextField *inputSecreatNubText = [[UITextField alloc]initWithFrame:CGRectMake(10, 0, kScreenWidth-30, 45)];
                    inputSecreatNubText.textAlignment = NSTextAlignmentLeft;
                    inputSecreatNubText.textColor = [UIColor grayColor];
                    inputSecreatNubText.placeholder = @"请输入密码";
                    inputSecreatNubText.delegate = self;
                    inputSecreatNubText.clearButtonMode = UITextFieldViewModeAlways;
                    inputSecreatNubText.secureTextEntry = YES;
                    self.inputSecreatText = inputSecreatNubText;
                    [view addSubview:inputSecreatNubText];
                    
                }
                if (i == 1) {
                    
                    UITextField *sureSecreatNubText = [[UITextField alloc]initWithFrame:CGRectMake(10, 0, kScreenWidth-30, 45)];
                    sureSecreatNubText.textAlignment = NSTextAlignmentLeft;
                    sureSecreatNubText.textColor = [UIColor grayColor];
                    sureSecreatNubText.placeholder = @"确定密码";
                    self.sureSecreatText = sureSecreatNubText;
                    sureSecreatNubText.clearButtonMode = UITextFieldViewModeAlways;
                    sureSecreatNubText.secureTextEntry = YES;
                    sureSecreatNubText.delegate = self;
                    [view addSubview:sureSecreatNubText];
                    
                    
                }
                
            }
            
        }
       
    }
    
}

- (void)getSecurityCode{
    
    Reachability *reach = [Reachability reachabilityForInternetConnection];
    NetworkStatus status = [reach currentReachabilityStatus];
    
    if (status == NotReachable) {
        
        MBProgressHUD *HUD = [MBProgressHUD showHUDAddedTo:KeyWindow animated:YES];
        HUD.labelText = @"请检查网络连接";
        HUD.mode = MBProgressHUDModeText;
        [HUD hide:YES afterDelay:1.0];
        
        return;
        
    }
 
    NSDictionary *params = @{@"username":self.inputPhoneNubText.text};
    [HttpTool postWithURL:@"http://61.135.176.43:6080/bigtobig/user/if_user_existed?" params:params success:^(id json) {
        
        NSString *str = json[@"count"];
        int a = [str intValue];
        NSLog(@"%@",str);
        
        if (a == 1) {
            
            [self yanzhengma];
            NSDictionary *params = @{@"username":self.inputPhoneNubText.text};
            
            [HttpTool postWithURL:@"http://61.135.176.43:6080/bigtobig/user/send_varify_code?" params:params success:^(id json) {
                NSLog(@"%@",json);
                
                NSData *data = [NSJSONSerialization dataWithJSONObject:json options:NSJSONWritingPrettyPrinted error:nil];
                
                NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
                NSLog(@"%@",dict);
                
                
            } failure:^(NSError *error) {
                
                MBProgressHUD *HUD = [MBProgressHUD showHUDAddedTo:KeyWindow animated:YES];
                HUD.labelText = @"网络请求失败";
                HUD.mode = MBProgressHUDModeText;
                [HUD hide:YES afterDelay:1.0];
                
            }];
            
        
        }else{
        
            MBProgressHUD *HUD = [MBProgressHUD showHUDAddedTo:KeyWindow animated:YES];
            HUD.labelText = @"账号未注册";
            HUD.mode = MBProgressHUDModeText;
            [HUD hide:YES afterDelay:1.0];

        }

    } failure:^(NSError *error) {
        
        
    }];

        NSLog(@"手机号码正确调接口发送验证码");
    

}


- (void)complate{
    
    
    if (self.inputSecreatText.text.length <6||self.inputSecreatText.text.length > 18) {
        
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        hud.mode = MBProgressHUDModeText;
        hud.labelText = @"密码长度需大于5位小于17位";
        [hud hide:YES afterDelay:1];
        
        
        
    }else if(![self.inputSecreatText.text isEqualToString: self.sureSecreatText.text]) {
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        hud.mode = MBProgressHUDModeText;
        hud.labelText = @"两次密码输入不一致";
        [hud hide:YES afterDelay:1];
        
        
    }else{
        
    NSDictionary *params = @{@"username":self.inputPhoneNubText.text,@"new_password":self.inputSecreatText.text};
        
    [HttpTool postWithURL:@"http://61.135.176.43:6080/bigtobig/user/reset_password?" params:params success:^(id json) {
        
        NSString *returnCode = [NSString stringWithFormat:@"%@",json[@"return_code"]];
        NSLog(@"%@",returnCode);
        
        [UIView animateWithDuration:1.0 animations:^{
            
            if ([returnCode isEqualToString:@"0"]) {
                
                [NSThread sleepForTimeInterval:1];
                MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
                hud.mode = MBProgressHUDModeText;
                hud.labelText = @"密码重置成功请重新登录";
                [hud hide:YES afterDelay:2];
                
            }
            
        } completion:^(BOOL finished) {
            
            [self.navigationController popViewControllerAnimated:YES];

            
        }];

      
      } failure:^(NSError *error) {
          
          
          MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
          hud.mode = MBProgressHUDModeText;
          hud.labelText = @"密码重置失败";
          [hud hide:YES afterDelay:2];
          
        [self.navigationController popViewControllerAnimated:YES];
          
      }];

    }
}
- (void)next{
    
    
    if (self.inputPhoneNubText.text.length == 0) {
        
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        hud.mode = MBProgressHUDModeText;
        hud.labelText = @"请输入账号";
        [hud hide:YES afterDelay:1];
        

    }else if(!([ZYUtils validateEmail:self.inputPhoneNubText.text]||[ZYUtils validateMobile:self.inputPhoneNubText.text])){
        
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        hud.mode = MBProgressHUDModeText;
        hud.labelText = @"账号为手机号或邮箱";
        [hud hide:YES afterDelay:1];
    
    }else if (self.inputSecurityCodeText.text.length == 0){
        
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        hud.mode = MBProgressHUDModeText;
        hud.labelText = @"请输入验证码";
        [hud hide:YES afterDelay:1];
        
    }else if(self.inputSecurityCodeText.text.length !=4){
        
        
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        hud.mode = MBProgressHUDModeText;
        hud.labelText = @"验证码为四位数字";
        [hud hide:YES afterDelay:1];
        
    }else{
        
        NSDictionary *params = @{@"username":self.inputPhoneNubText.text,@"code":self.inputSecurityCodeText.text};
        
        [HttpTool postWithURL:@"http://61.135.176.43:6080/bigtobig/user/varify_code?" params:params success:^(id json) {
            NSLog(@"%@",json);
            NSData *data = [NSJSONSerialization dataWithJSONObject:json options:NSJSONWritingPrettyPrinted error:nil];
            
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
            NSLog(@"%@",dict);
            
            NSString *str = dict[@"return_code"];
            NSString  *return_code = [NSString stringWithFormat:@"%@",str];
            if ([return_code isEqualToString:@"0"]) {
                
                [self.scrollView setContentOffset:CGPointMake(kScreenWidth, 0) animated:YES];
                
            }else{
                
                MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
                hud.mode = MBProgressHUDModeText;
                hud.labelText = @"请重新输入验证码";
                [hud hide:YES afterDelay:1];
            }
            
            
        } failure:^(NSError *error) {
            
            
                MBProgressHUD *HUD = [MBProgressHUD showHUDAddedTo:KeyWindow animated:YES];
                HUD.labelText = @"网络请求失败";
                HUD.mode = MBProgressHUDModeText;
                [HUD hide:YES afterDelay:1.0];
                
            
        }];

    

    }
}
-(void)yanzhengma{
    
    __block int timeout=30; //倒计时时间
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(_timer, ^{
        if(timeout<=0){ //倒计时结束，关闭
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                [self.getSecurityCodeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
                self.getSecurityCodeBtn.userInteractionEnabled = YES;
//                self.getSecurityCodeBtn.backgroundColor = COLOR_RGBA(253, 82, 75, 1);
                self.getSecurityCodeBtn.userInteractionEnabled = YES;
            });
        }else{
            //            int minutes = timeout / 60;
            int seconds = timeout % 60;
            NSString *strTime = [NSString stringWithFormat:@"%.2d", seconds];
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                // NSLog(@"____%@",strTime);
                [self.getSecurityCodeBtn setTitle:[NSString stringWithFormat:@"%@秒重新发送",strTime] forState:UIControlStateNormal];
//                self.getSecurityCodeBtn.backgroundColor = [UIColor grayColor];
                self.getSecurityCodeBtn.userInteractionEnabled = NO;
                
            });
            timeout--;
            
        }
    });
    dispatch_resume(_timer);
    
}

///调用方法  设置只能输入数字  和   限制字符长度
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    //身份证  只能输入数字 限制字数18位
    //    textField.keyboardAppearance =  UIKeyboardTypeNumberPad;
    
    if(textField == self.inputSecurityCodeText){
        
        //        textField
        NSUInteger lengthOfString = string.length;
        for (NSInteger loopIndex = 0; loopIndex < lengthOfString; loopIndex++) {//只允许数字输入
            unichar character = [string characterAtIndex:loopIndex];
            if (character < 48) return NO; // 48 unichar for 0
            if (character > 57) return NO; // 57 unichar for 9
        }
        NSUInteger proposedNewLength = textField.text.length - range.length + string.length;
        
        if (proposedNewLength > 4)
            
            return NO;//限制长度
    }
//    }if (self.inputPhoneNubText == textField) {
//        
//        NSUInteger proposedNewLength = textField.text.length - range.length + string.length;
//
//        if (proposedNewLength > 11)
//            
//            return NO;//限制长度
//
//    }
        if (self.inputSecreatText == textField) {
        
        NSUInteger proposedNewLength = textField.text.length - range.length + string.length;
        
        if (proposedNewLength > 18)
            
            return NO;//限制长度
        
    }if (self.sureSecreatText == textField) {
        NSUInteger proposedNewLength = textField.text.length - range.length + string.length;
        
        if (proposedNewLength > 18)
            
            return NO;//限制长度
        
    }

    
    return YES;
}

// 实现UIScrollView的滚动方法
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    
    // 1. 获取滚动的x方向的偏移值
    CGFloat offsetX = scrollView.contentOffset.x;
    // 用已经偏移了得值, 加上半页的宽度
    offsetX = offsetX + (kScreenWidth * 0.5);
    
    // 2. 用x方向的偏移的值除以一张图片的宽度(每一页的宽度)，取商就是当前滚动到了第几页（索引）
    NSLog(@"11111111%f",offsetX);
    NSInteger page = offsetX / kScreenWidth;
    
    // 3. 将页码设置给UIPageControl
    self.pageControl.currentPage = page;
    NSLog(@"%ld",page);
    
}


- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    
    // 1. 获取当前的UIPageControl的页码
    NSInteger page = self.pageControl.currentPage;
    
    // 3. 用每页的宽度 * (页码 + 1) == 计算除了下一页的contentOffset.x
    CGFloat offsetX = page * self.scrollView.frame.size.width;
    NSLog(@"%f",offsetX);
    // 4. 设置UIScrollView的contentOffset等于新的偏移的值
    [self.scrollView setContentOffset:CGPointMake(offsetX, 0) animated:YES];
    
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    
    //回退键盘
    return [textField endEditing:YES];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
    [self.inputPhoneNubText endEditing:YES];
    [self.inputSecreatText endEditing:YES];
//    [self.inputNameNubText endEditing:YES];
    [self.sureSecreatText endEditing:YES];
    [self.inputSecurityCodeText endEditing:YES];
}

@end
